package aes.client;

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.*;

import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;

import common.*;

public class ReportTeacherUI extends JPanel implements ActionListener, ListSelectionListener, Observer {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2779330512178375585L;

	private ClientUI ui;
	private Client c;

	private JButton btnBack;
	private JButton btnExamInfo;
	private JTable list;
	private int code;

	public ReportTeacherUI(Client c,ClientUI ui){
		this.c = c;
		this.ui = ui;
		JFrame frame = new JFrame();
		frame.setSize(640, 480);
		frame.add(this);

		// Handle messages from server.
		c.addObserver(this);

		setLayout(new GridBagLayout());

		JPanel panel = new JPanel();
		panel.setBorder(new LineBorder(new Color(0, 0, 0), 2, true));
		panel.setPreferredSize(new Dimension(600,400));

		GridBagConstraints gbc_panel = new GridBagConstraints();
		gbc_panel.insets = new Insets(5, 0, 5, 0);
		gbc_panel.gridx = 0;
		gbc_panel.gridy = 0;
		add(panel,gbc_panel);
		GridBagLayout gbl_panel = new GridBagLayout();
		gbl_panel.rowWeights = new double[]{0.0, 1.0};
		gbl_panel.columnWeights = new double[]{0.0, 1.0};
		panel.setLayout(gbl_panel);

		JLabel lblTitle = new JLabel("Teacher Reports and Analysis");
		lblTitle.setVerticalAlignment(SwingConstants.TOP);
		lblTitle.setHorizontalAlignment(SwingConstants.CENTER);
		lblTitle.setBounds(7, 10, 70, 17);
		lblTitle.setFont(new Font("Tahoma", Font.BOLD, 14));

		GridBagConstraints gbc_lblTitle = new GridBagConstraints();
		gbc_lblTitle.gridwidth = 4;
		gbc_lblTitle.fill = GridBagConstraints.BOTH;
		gbc_lblTitle.insets = new Insets(5, 0, 5, 5);
		gbc_lblTitle.gridx = 0;
		gbc_lblTitle.gridy = 0;
		panel.add(lblTitle, gbc_lblTitle);

		list = new JTable(){
			/**
			 * 
			 */
			private static final long serialVersionUID = -5848421012480878482L;

			public boolean isCellEditable(int rowIndex, int colIndex) {
				return false; //Disallow the editing of any cell
			}};
			list.setModel(new DefaultTableModel(
					new Object[][] {
					},
					new String[] {
							"Execution Code" , "Exam ID"
					}
					) {
				/**
				 * 
				 */
				private static final long serialVersionUID = -4567261985989300298L;
				@SuppressWarnings("rawtypes")
				Class[] columnTypes = new Class[] {
					String.class, String.class, String.class , String.class 
				};
				@SuppressWarnings({ "unchecked", "rawtypes" })
				public Class getColumnClass(int columnIndex) {
					return columnTypes[columnIndex];
				}
			});
			list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
			list.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
			list.getColumnModel().getColumn(0).setPreferredWidth(70);
			list.getColumnModel().getColumn(1).setPreferredWidth(80);
			list.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
			JScrollPane scrollPane = new JScrollPane(list);
			list.setFillsViewportHeight(true);
			list.getSelectionModel().addListSelectionListener(this);
			GridBagConstraints gbc_list = new GridBagConstraints();
			gbc_list.insets = new Insets(5, 5, 5, 5);
			gbc_list.fill = GridBagConstraints.BOTH;
			gbc_list.gridwidth = 4;
			gbc_list.gridx = 0;
			gbc_list.gridy = 1;
			panel.add(scrollPane, gbc_list);

			btnBack = new JButton("Back", new ImageIcon(ExamsManagerUI.class.getResource("/aes/client/images/back.png")));
			btnBack.addActionListener(this); 
			GridBagConstraints gbc_btnBack = new GridBagConstraints();
			gbc_btnBack.insets = new Insets(5, 5, 5, 5);
			gbc_btnBack.gridx = 0;
			gbc_btnBack.gridy = 3;
			panel.add(btnBack, gbc_btnBack);
			btnBack.setBounds(353, 7, 57, 23);

			btnExamInfo = new JButton("Exam Info", new ImageIcon(ExamsManagerUI.class.getResource("/aes/client/images/Exam.png")));
			btnExamInfo.addActionListener(this); 
			GridBagConstraints gbc_btnExamInfo = new GridBagConstraints();
			gbc_btnExamInfo.insets = new Insets(5, 5, 5, 5);
			gbc_btnExamInfo.gridx = 3;
			gbc_btnExamInfo.gridy = 3;
			panel.add(btnExamInfo, gbc_btnExamInfo);
			btnExamInfo.setBounds(353, 7, 57, 23);
	}

	/**
	 * Updates exams list
	 * 
	 * @see this function is thread safed, so use it in order to update interface from the other thread
	 */
	public void UpdateUI() {
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				getExamsList();  
			}
		});
	}

	/**
	 * Load Exams list from the server
	 */
	@SuppressWarnings("static-access")
	private void getExamsList() {
		CommandMessage msg = new CommandMessage(CommandMessage.GET_TEACHER_REPORT, new String[] {Integer.toString(ui.getUser().getId())});
		try {
			c.sendToServer(msg);
		} catch (IOException e) {
			e.printStackTrace();
			ui.ShowMessageBox("Error", "Can't retrieve exams list", JOptionPane.ERROR_MESSAGE);
		}
	}

	@SuppressWarnings("static-access")
	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource().equals(btnBack)) {
			// Back.
			ui.SetContent(ui.MAIN_SCREEN);
		}
		else if (e.getSource().equals(btnExamInfo)) {
			DefaultTableModel model =(DefaultTableModel) list.getModel();
			Vector<?> o1 = (Vector<?>) model.getDataVector().get(list.getSelectedRow());
			code = Integer.parseInt((String)o1.get(0));
			CommandMessage ms = new CommandMessage(CommandMessage.VERIFY_EXAM_INFO,new Object[]{code});
			try {
				c.sendToServer(ms);
			}
			catch (IOException e2) {
				e2.printStackTrace();
			}
		}
	}



	@Override
	public void update(Observable arg0, Object arg1) {
		if (arg1 instanceof CommandMessage) {
			CommandMessage ms=(CommandMessage)arg1;
			if (ms.getCommand().equals(CommandMessage.ACKNOWLEDGE_MESSAGE) && ((String)ms.getParams()[0]).equals(CommandMessage.GET_TEACHER_REPORT)){
				//gets Questions array from server answer (query answer from __ )
				@SuppressWarnings("unchecked")
				ArrayList<Integer[]> exams = (ArrayList<Integer[]>) ms.getParams()[1];
				//disables button
				btnExamInfo.setEnabled(false); 
				if (exams != null) {
					// Bind data.
					DefaultTableModel model =(DefaultTableModel) list.getModel();
					model.setRowCount(0);
					for (Integer[] e:exams) {
						String[] row = new String[2];
						row[0] = e[0].toString();
						row[1] = String.format("%06d", e[1].intValue());
						model.addRow(row);
					}
					list.setModel(model);
				}
			}
			else if(ms.getCommand().equals(CommandMessage.ACKNOWLEDGE_MESSAGE) && ((String)ms.getParams()[0]).equals(CommandMessage.VERIFY_EXAM_INFO)){
				if((Boolean) ms.getParams()[1]==true){
					ui.SetContent(ui.TEACHER_REPORT_EXAM_INFO_SCREEN);
					ReportTeacherInfoUI panel= ((ReportTeacherInfoUI)ui.getContentPane());
					panel.setExecutionCode(code);
				}else{
					ClientUI.ShowMessageBox("Information", "Exam report isn't ready" ,JOptionPane.INFORMATION_MESSAGE);
				}
			}
		}
	}

	/**
	 * Exams list selected item changed event handler
	 */
	@Override
	public void valueChanged(ListSelectionEvent e) {
		btnExamInfo.setEnabled(true);
	}

}